module SessionsHelper
  def login(user)
    session[:user_id] = user.id
    cookies.permanent.signed[:usr_id] = user.id
  end

  def login?
    (session[:user_id] || cookies.signed[:user_id]) && User.find_by_id(session[:user_id])
  end

  def login_auth
    redirect_to user_auth_path unless login?
  end

  def auth_user(user, password)
    # user.password == User.password_digest(password)
    password_digest = BCrypt::Password.new(user.password)
    # Rails.logger.debug "auth_user result: #{password_digest == password} password = #{password}"
    password_digest == password
  end

  def logout
    session.delete(:user_id)
    cookies.delete(:user_id)
  end
  def current_user
    if session[:user_id]
      @current_user ||= User.find_by_id(session[:user_id])
    elsif cookies.signed[:user_id]
      user = User.find_by_id(cookies.signed[:user_id])
      login user
      @current_user = user
    end
    @current_user
  end

  def current_group
    @current_group ||= Group.find_by_id(current_user.group_id)
  end
end
